package com.heima.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.message.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.Feign.ApAuthorFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.common.ApUserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 用户关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //校验参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取用户信息 判断是否为游客
        ApUser user = ApUserThreadLocal.getUser();
        if (null == user || null == user.getId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取作者用户信息
        ApAuthor apAuthor = apAuthorFeign.selectById(dto.getAuthorId());
        if (null == apAuthor) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer authorId = apAuthor.getUserId();

        //获取当前用户详细信息
        ApUser apUser = apUserMapper.selectById(user.getId());

        //判断是关注还是取消关注
        if (dto.getOperation() == 0) {
            //关注
            return followByUserId(authorId, apUser, dto.getArticleId());
        } else {
            //取消关注
            return followCancelByUserId(authorId, apUser);
        }
    }

    /**
     * 关注
     *
     * @param authorId
     * @param apUser
     * @return
     */
    private ResponseResult followByUserId(Integer authorId, ApUser apUser, Long articleId) {

        //判断关注表是否存在数据
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, authorId));
        if (null != apUserFollow) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //判断粉丝表是否存在数据
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, authorId).eq(ApUserFan::getFansId, apUser.getId()));
        if (null != apUserFan) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //保存关注表数据
        apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(apUser.getId());
        apUserFollow.setFollowId(authorId);
        apUserFollow.setFollowName(apUser.getName());
        apUserFollow.setLevel((short) 1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setCreatedTime(new Date());

        apUserFollowMapper.insert(apUserFollow);

        //保存粉丝表数据
        apUserFan = new ApUserFan();
        apUserFan.setUserId(authorId);
        apUserFan.setFansId(Long.valueOf(apUser.getId()));
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel((short) 1);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setIsDisplay(true);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);

        apUserFanMapper.insert(apUserFan);

        // 记录关注行为
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setFollowId(authorId);
        dto.setArticleId(articleId);
        dto.setUserId(apUser.getId());

        //异步发送消息，保存关注行为
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消关注
     *
     * @param authorId
     * @param apUser
     * @return
     */
    private ResponseResult followCancelByUserId(Integer authorId, ApUser apUser) {
        //判断关注表是否存在数据
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, authorId));
        if (null == apUserFollow) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断粉丝表是否存在数据
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, authorId).eq(ApUserFan::getFansId, apUser.getId()));
        if (null == apUserFan) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //删除关注表数据
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, authorId));

        //删除粉丝表数据
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, authorId).eq(ApUserFan::getFansId, apUser.getId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
